import tensorflow as tf
from tensorflow.keras import datasets
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras import models, regularizers
from tensorflow.keras import optimizers

def generate_sequence_data(num_sampless=1000, sequence_length=20):
    X = np.random.randint(0, 2, size=(num_sampless, sequence_length, 1))
    y = np.zeros((num_sampless, sequence_length, 1))
    for i in range(num_sampless):
        for t in range(2, sequence_length):
            y[i, t, 0] = X[i, t-1, 0] ^ X[i, t-2, 0]  # 异或操作
    return X.astype(np.float32), y.astype(np.float32)

# 生成训练和测试数据
X_train, y_train = generate_sequence_data(800, 20)
X_test, y_test = generate_sequence_data(200, 20)
# 构建SRN模型
model = tf.keras.Sequential()
model.add(tf.keras.layers.Embedding(input_dim=1000, output_dim=100, input_length=20))
model.add(tf.keras.layers.SimpleRNN(64, return_sequences=True, input_shape=(20, 1)))
model.add(tf.keras.layers.SimpleRNN(32, return_sequences=True))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, batch_size=32, epochs=50, validation_data=(X_test, y_test), verbose=1)
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f'\n测试集准确率：{test_accuracy:.4f}')

